from pydantic import BaseModel, Field
from typing import Optional
import uvicorn
from fastapi import FastAPI

class Item(BaseModel):
    # 商品名称字段
    name: str = Field(..., example="手机", description="商品名称", title="商品名")
    # 商品价格字段，必须大于0
    price: float = Field(..., gt=0, example=2999.0, description="商品价格，必须大于0", title="价格")
    # 商品详细描述字段，为可选字段
    description: Optional[str] = Field(default=None, example="这是一款高性能智能手机", description="商品详细描述，可选", title="描述")
    # 商品类别字段
    category: str = Field(example="电子产品", description="商品所属类别", title="类别")


app = FastAPI()
# 在路径操作函数中使用模型
@app.post("/items/",response_model=Item, summary="创建一个商品", description="创建一个商品，需要提供商品的相关信息")  # response_model 指定成功响应返回的形状
async def create_item(item: Item):
    '''
    描述测试
    '''
    # ... 处理逻辑
    return item


#======================================================================================================
from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime

# 简洁的模型定义
class ItemCreate(BaseModel):
    name: str = Field(..., min_length=1, max_length=100, example="智能手机")
    price: float = Field(..., gt=0, example=2999.99)
    description: Optional[str] = Field(None, max_length=1000, example="高性能智能手机")
    stock: int = Field(0, ge=0, example=100)
    is_active: bool = Field(True, example=True)

# 响应模型简洁写法
class ItemResponse(ItemCreate):
    id: int = Field(..., example=1)
    created_at: datetime = Field(..., example="2023-01-01T12:00:00Z")
    updated_at: datetime = Field(..., example="2023-01-01T12:00:00Z")

from pydantic import field_validator
@field_validator('password')
def validate_password(cls, v):
    if len(v) < 8:
        raise ValueError('密码长度至少8位')
    return v

# 简洁的分页响应模型
from fastapi import Query

from pydantic import BaseModel
from typing import TypeVar, Generic

T = TypeVar('T')
class Response(BaseModel, Generic[T]):
    data: T
    success: bool


@app.post("/items2/", response_model=ItemResponse,description="创建一个new商品")
async def create_item(item: ItemCreate):
    """创建新商品"""
    # 业务逻辑
    return {**item.dict(), "id": 1, "created_at": datetime.now(), "updated_at": datetime.now()}

@app.get("/items/", response_model=Response[ItemResponse])
async def get_items(
    page: int = Query(1, ge=1),
    size: int = Query(10, ge=1, le=100)
):
    """获取商品分页列表"""
    # 业务逻辑
    return {
        "items": [],
        "total": 0,
        "page": page,
        "size": size
    }


if __name__ == '__main__':
    uvicorn.run(app, host="127.0.0.1", port=8000)
    # http://127.0.0.1:8000/docs